# -*- coding: utf-8 -*-

from nose.tools.trivial import ok_, eq_

from common.config import cfg
from grail import step
from common.utils import wait
from wgni.steps.login import LoginSteps

from wgq.pages.home import HomePage
from wgq.pages.my_profile import MyProfile


class CommonSteps(object):
    home_page = HomePage()
    my_profile_page = MyProfile()
    login_steps = LoginSteps()

    @step(step_group=True)
    def login_to_wgq_as(self, account):
        self.open_wgq_home_page()
        self.click_login_link()
        self.login_steps.submit_login_form(account)
        self.wait_for_user_is_logged_in(account)

    @step(step_group=True)
    def login_to_wgq_using_request(self, account):
        self.login_steps.login_to_wgni_using_request(
            account, url_to_redirect=self.home_page.url)
        self.wait_for_user_is_logged_in(account)

    @step
    def open_wgq_home_page(self):
        self.home_page.open()

    @step
    def click_login_link(self):
        self.home_page.login_link.click()

    @step
    def wait_for_user_is_logged_in(self, account):
        wait(lambda: self.home_page.is_element_present(
            'username_link') and self.home_page.username_link.text == account.name,
            waiting_for='user {0} to authorize at wargag'.format(account.name))

    @step
    def verify_user_is_not_logged_in(self):
        ok_(self.home_page.is_element_present('login_link', timeout=cfg.timeout),
            msg='User is authorized')

    @step
    def open_user_profile(self):
        self.home_page.my_profile_link.click()

    @step
    def verify_is_this_user_profile(self, account):
        eq_(self.my_profile_page.profile_username.text, account.name,
            'Expected username[%s], but actual[%s]' % (account.name, self.my_profile_page.profile_username.text))

    @step
    def logout_from_wgq(self):
        self.home_page.username_link.click()
        self.home_page.logout.click()
